<?php

require_once '../application/controllers/MotherController.php';
require_once APPLICATION_PATH . '/modules/Invoice/models/Invoice.php';

class Invoice_IndexController extends MotherController {

    public function init() {
        if (!isset($_SESSION['SecureLogin'])) {
            $this->_redirect('/Admin/index/login');
        }
        $this->view->categorie = $this->_categorie('invoice');

        $this->_helper->layout->setLayout('2columns-left');
    }

    public function indexAction() {
        $modelFacture = new Invoice_Model_Invoice();
        $this->view->invoices = $modelFacture->getInvoiceByClient($_SESSION['SecureLogin']['id']);
        $this->view->messages = $this->_helper->flashMessenger->getMessages();

        unset($modelFacture);
    }

    public function createAction() {
        $this->view->headTitle(' - Créer facture');
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            $this->view->value = $formData;

            //Enregistre la facture
            $modelInvoice = new Invoice_Model_Invoice();
            $this->view->msg = $result = $modelInvoice->saveFacture($formData['facture']);

            if ($result)
                $this->_flashMessage('Votre facture a bien été créée');
        }
        unset($modelFacture);
    }

    public function updateAction() {
        $invoiceID = $this->_getParam('id', false);
        $this->view->headTitle(' - Modifie la facture ' . $invoiceID);
        $this->view->id = $invoiceID;

        $modelInvoice = new Invoice_Model_Invoice();

        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            $this->view->value = $formData;
            //Modifie la facture
            $this->view->msg = $result = $modelInvoice->update($invoiceID, $formData['facture']);
            if ($result)
                $this->_flashMessage("La facture $invoiceID a bien été modifiée");
        } elseif ($invoiceID) {
            $invoice = $modelInvoice->getInvoice($invoiceID);
            $invoiceData = array();
            $invoiceData['facture'] = $modelInvoice->XMLtoString($invoice);
            $this->view->value = $invoiceData;
        }
        unset($modelInvoice);
    }

    public function deleteAction() {
        $invoiceID = $this->_getParam('id', false);
        $modelInvoice = new Invoice_Model_Invoice();
        $result = $modelInvoice->delete($invoiceID);
        unset($modelInvoice);

        $msg = ($result) ? "La facture $invoiceID a bien été supprimée" : "La facture $invoiceID non existante";
        if ($result)
            $this->_flashMessage($msg);
    }

    private function _flashMessage($msg) {
        $this->_helper->flashMessenger->addMessage($msg);
        $this->_helper->redirector('index');
    }

}

